package jjn.round2;

import commons.TreeNode;

import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;

/**
 * @author Jiang Jining
 * @since 2023-05-03 21:25
 */
public class Offer32_3_LevelOrder3 {
    public List<List<Integer>> levelOrder(TreeNode root) {
        Deque<TreeNode> queue = new LinkedList<>();
        List<List<Integer>> result = new ArrayList<>();
        if (root == null) {
            return result;
        }
        queue.offer(root);
        int rowNumber = 1;
        while (!queue.isEmpty()) {
            // 奇数行
            List<Integer> level = new ArrayList<>();
            int size = queue.size();
            if (rowNumber % 2 == 1) {
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = queue.pollFirst();
                    if (treeNode != null) {
                        level.add(treeNode.val);
                        if (treeNode.left != null) {
                            queue.offerLast(treeNode.left);
                        }
                        if (treeNode.right != null) {
                            queue.offerLast(treeNode.right);
                        }
                    }
                }
                
            } else {
                for (int i = 0; i < size; i++) {
                    TreeNode treeNode = queue.pollLast();
                    if (treeNode != null) {
                        level.add(treeNode.val);
                        if (treeNode.right != null) {
                            queue.offerFirst(treeNode.right);
                        }
                        if (treeNode.left != null) {
                            queue.offerFirst(treeNode.left);
                        }
                    }
                }
            }
            rowNumber++;
            result.add(level);
        }
        return result;
    }
}
